package co.sanduche.teach.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.content.Context;
import android.util.Log;
import co.sanduche.models.Enums.ChannelType;
import co.sanduche.models.Models;
import co.sanduche.models.Models.Photo;
import co.sanduche.models.Models.Post;
import co.sanduche.services.EndPoints;
import co.sanduche.teach.gallery.GalleryDBOpenHelper;
import co.sanduche.teach.gallery.ImageItem;
import co.sanduche.teach.gallery.PostDBHelper;
import co.sanduche.teach.service.ServiceManager.ServiceBinder;
import co.sanduche.util.EPFuture;
import co.sanduche.vos.Tuple;

public class PostTask extends TaskExecutor {

	protected long id;
	private PostDBHelper postDbHelper;
	private GalleryDBOpenHelper galleryDBHelper;
	private ServiceBinder binder;

	public PostTask() {
	}

	@Override
	public void init(Context context, ServiceBinder binder, Task t) {
		this.id = t.getEntityId();
		postDbHelper = new PostDBHelper(context);
		galleryDBHelper = new GalleryDBOpenHelper(context);
		this.binder = binder;

	}

	public void execute() throws Exception {
		Post mensaje = new Post();
		AndroidPost ap = postDbHelper.get(id);

		HashSet<Models.PostChannel> recipients = new HashSet<Models.PostChannel>();

		mensaje.setChannels(recipients);

		for (Tuple<ChannelType, Long> tupp : ap.postChannels) {

			Models.PostChannel r = new Models.PostChannel();
			r.setChannelType(tupp.getX());
			r.setIdChannel(tupp.getY());
			recipients.add(r);
		}
		List<Photo> photos = new ArrayList<Models.Photo>();
		for (Long idPhoto : ap.photos) {
			Models.Photo photo = new Models.Photo();
			ImageItem ii = galleryDBHelper.get(idPhoto);
			photo.setId(ii.getServerId());
			photos.add(photo);
		}

		mensaje.setPhotos(photos);

		Log.i(getClass().getSimpleName(),
				"ENVIANDO!!!!!" + mensaje.getPublished());
		EPFuture<Post> future = EPFuture.newFuture();
		EndPoints.PostsEP.post(mensaje, future);
		Post data = future.get();
		binder.showMessage("Mensaje enviado");
		ap.serverId = data.getId();
		postDbHelper.update(ap);
	}
}
